package com.nandi.deviceinstall.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import androidx.recyclerview.widget.GridLayoutManager
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.nandi.deviceinstall.R
import com.nandi.deviceinstall.base.BaseMvpActivity
import com.nandi.deviceinstall.contract.EquimentStepContract
import com.nandi.deviceinstall.presenter.EquipmentStepPresenter
import kotlinx.android.synthetic.main.toolbar_back_include.*
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.Basemap
import kotlinx.android.synthetic.main.activity_equipment_step.*
import com.esri.arcgisruntime.mapping.view.LocationDisplay
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.nandi.deviceinstall.bean.*
import com.nandi.deviceinstall.common.Constant
import com.nandi.deviceinstall.net.dto.TapAddDTO
import com.nandi.deviceinstall.util.SharedTool
import com.nandi.deviceinstall.util.SxTransformUtils
import com.nandi.deviceinstall.weight.InitDataListener
import com.nandi.deviceinstall.weight.imagepicker.*
import kotlinx.android.synthetic.main.equipment_step_dialog.view.*
import java.io.File
import java.util.ArrayList
import android.text.Editable
import android.text.TextWatcher
import com.afollestad.materialdialogs.MaterialDialog
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.nandi.deviceinstall.util.CustomToast
import kotlinx.android.synthetic.main.activity_equipment_step.disasterName
import kotlinx.android.synthetic.main.activity_equipment_step.disasterNum
import kotlinx.android.synthetic.main.activity_equipment_step.district
import kotlinx.android.synthetic.main.activity_equipment_step.img_show
import kotlinx.android.synthetic.main.activity_equipment_step.mapView
import kotlinx.android.synthetic.main.activity_equipment_step.township
import kotlinx.android.synthetic.main.dialog_tips.view.*


class EquipmentStepActivity : BaseMvpActivity<EquipmentStepPresenter>(), EquimentStepContract.View {



    private lateinit var mLocationDisplay: LocationDisplay
    private val maxImgCount = 1 // 最大选择图片数量
    private var selImageList: MutableList<ImageItem> = ArrayList() //图片集合
    private var deleteImageList: MutableList<ImageItem> = ArrayList() //删除图片集合
    private lateinit var adapter: ImagePickerAdapter
    private var listCitys: MutableList<CityBean.DataBean> = mutableListOf()
    private var listTowns: MutableList<TownBean.DataBean> = mutableListOf()
    private var citys = mutableListOf<String>()
    private var towns = mutableListOf<String>()
    private var disastersName = mutableListOf<String>()
    private var disastersNu = mutableListOf<String>()
    private lateinit var cityAdapter: ArrayAdapter<String>
    private lateinit var townAdapter: ArrayAdapter<String>
    private lateinit var disasterNameAdapter: ArrayAdapter<String>
    private lateinit var disasterNuAdapter: ArrayAdapter<String>
    //private var isDisasterName = false
    private lateinit var monitorNo: String
    private val strSerialNumber = arrayOf("01", "02", "03", "04", "05", "06", "07", "08", "09", "10")
    private val strMonitorType = arrayOf("地表裂缝监测仪", "墙裂缝监测仪", "地面倾斜监测仪", "降雨量监测仪", "泥位监测仪")
    private val strMonitorNo = arrayOf("ZDL", "ZQL", "ZQX", "ZYL", "ZNW")
    private var picString = "" //相对路径
    private lateinit var action: String
    private var tapInfo = TapRecordInfoBean()
    private lateinit var v: Viewpoint
    //private lateinit var cityNames: String
    private var mGraphicsOverlay: GraphicsOverlay = GraphicsOverlay()
    private var isLocation = false
    private var isSelectCity = false
    private var isSelectTown = false
    private var isFirstUpdate = false
    private var token = ""

    override val layoutId: Int
        get() = R.layout.activity_equipment_step

    override fun initView() {
        token = SharedTool.get(context, Constant.TOKEN, "") as String
        mPresenter = EquipmentStepPresenter()
        mPresenter.attachView(this)
        action = intent!!.extras!!.getString("action")!!
        initAdapter()
        initListener()
        setupMap()
        initImagePicker()
        mPresenter.requestListCity(token, "")
        if ("add" == action) {
            tv_title_toolbar.text = "设备安装踩点"

            title_image.visibility = View.VISIBLE
            setupLocationDisplay()
        } else if ("update" == action) {
            tapInfo = intent!!.extras!!.getSerializable("tapInfo") as TapRecordInfoBean
            tv_title_toolbar.text = "踩点信息修改"

            ll_right.visibility = View.GONE
            initData()
        }
    }

    private fun initData() {
        isFirstUpdate = true
        //cityNames = tapInfo.data!!.cityName.toString()
        district.text = tapInfo.data!!.cityName
        district.setTextColor(Color.BLACK)
        district.textSize = 18f

        township.text = tapInfo.data!!.townName
        township.setTextColor(Color.BLACK)
        township.textSize = 18f

        village.setText(tapInfo.data!!.village)
        village.setTextColor(Color.BLACK)
        village.textSize = 18f

        disasterName.setText(tapInfo.data!!.disasterName)
        disasterName.setTextColor(Color.BLACK)
        disasterName.textSize = 18f

        disasterNum.text = tapInfo.data!!.disNo
        disasterNum.setTextColor(Color.BLACK)
        disasterNum.textSize = 18f

        monitorType.text = strMonitorType[tapInfo.data!!.monitorType!!.toInt()]
        monitorType.setTextColor(Color.BLACK)
        monitorType.textSize = 18f

        serialNumber.text = tapInfo.data!!.monitorNo!!.substring(tapInfo.data!!.monitorNo!!.length - 2, tapInfo.data!!.monitorNo!!.length)
        serialNumber.setTextColor(Color.BLACK)
        serialNumber.textSize = 18f

        val imageItem = ImageItem()
        imageItem.name = tapInfo.data!!.pointPic!!.substring(tapInfo.data!!.pointPic!!.lastIndexOf("/") + 1)
        imageItem.path = "${Constant.fileUrl}${tapInfo.data!!.pointPic}&type=6"
        picString = tapInfo.data!!.pointPic!!
        selImageList.clear()
        selImageList.add(imageItem)
        adapter.images = selImageList
        setLocationPointOverlay(tapInfo.data!!.monitorLng, tapInfo.data!!.monitorLat)
        isFirstUpdate = false
    }

    /**
     * 初始化图片选择器
     */
    private fun initImagePicker() {
        val imagePicker = ImagePicker.getInstance()
        //设置图片加载器
        imagePicker.imageLoader = GlideImageLoader()
        //显示拍照按钮
        imagePicker.isShowCamera = true
        //允许裁剪（单选才有效）
        imagePicker.isCrop = false
        //是否按矩形区域保存
        imagePicker.isSaveRectangle = true
        //选中数量限制
        imagePicker.selectLimit = maxImgCount
        //多选
        imagePicker.isMultiMode = false

        adapter = ImagePickerAdapter(this, selImageList, maxImgCount)
        adapter.setOnItemClickListener { _, position ->
            when (position) {
                IMAGE_ITEM_ADD -> {

                    ImagePicker.getInstance().selectLimit = maxImgCount - selImageList.size
                    val intent1 = Intent(context, ImageGridActivity::class.java)
                    startActivityForResult(intent1, REQ_CODE_SELECT)//打开选择,本次允许选择的数量

                }
                else -> {
                    //打开预览
                    val intentPreview = Intent(context, ImagePreviewDelActivity::class.java)
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, adapter.images as ArrayList<ImageItem>)
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position)
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true)
                    startActivityForResult(intentPreview, REQ_CODE_PREVIEW)
                }

            }
        }
        img_show.layoutManager = GridLayoutManager(this, 3)
        img_show.setHasFixedSize(true)
        img_show.adapter = adapter
    }

    private fun initAdapter() {
        val serialNumberAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strSerialNumber)
        val monitorTypeAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strMonitorType)
        serialNumber.setAdapter(serialNumberAdapter)
        monitorType.setAdapter(monitorTypeAdapter)
    }

    private fun setupLocationDisplay() {
        mLocationDisplay = mapView.locationDisplay
        mLocationDisplay.autoPanMode = LocationDisplay.AutoPanMode.COMPASS_NAVIGATION
        mLocationDisplay.addLocationChangedListener { p0 ->
            if (!isLocation) {
                val x = p0?.location?.position?.x
                lon.text = x.toString()
                val y = p0?.location?.position?.y
                lat.text = y.toString()
                if (x != null && y != null) {
                    val locationAddress = SxTransformUtils.getLocationAddress(context, x, y)
                    district.text = locationAddress
                    district.setTextColor(Color.BLACK)
                    district.textSize = 18f
                    isLocation = true
                }
            }
        }
        mLocationDisplay.startAsync()
    }

    private fun setupMap() {
        if (mapView != null) {
            ArcGISRuntimeEnvironment.setLicense("runtimelite,1000,rud6849747514,none,0JMFA0PL4S2HLMZ59106")
            mapView.isAttributionTextVisible = false
            val basemapType = Basemap.Type.IMAGERY
            val latitude = 29.09042
            val longitude = 106.71511
            val levelOfDetail = 11
            val map = ArcGISMap(basemapType, latitude, longitude, levelOfDetail)
            mapView.map = map
        }
    }

    private fun initListener() {
        //跳转记录
        title_image.setOnClickListener {
            startActivity(Intent(context, TapRecordActivity::class.java))
        }
        //返回
        iv_back_toolbar.setOnClickListener {
            var content = ""
            if ("add" == action) {
                content = "返回后将清空已填内容,确认返回？"
            } else if ("update" == action) {
                content = "修改内容不会被保存,确认返回？"
            }
            MaterialDialog.Builder(this)
                    .title("提示")
                    .content(content)
                    .positiveText("确认")
                    .negativeText("取消")
                    .onPositive { _, _ -> finish() }
                    .show()
        }
        //上传
        upload_equipment_step.setOnClickListener {

            if (checkInfo()) return@setOnClickListener

            if (selImageList.isEmpty()) {
                CustomToast.showToast(context,"请选择图片")
                return@setOnClickListener
            }

            initDialog()
        }

        location.setOnClickListener {
            if ("update" == action) {
                setupLocationDisplay()
            } else {
                v = Viewpoint(lat.text.toString().toDouble(),
                        lon.text.toString().toDouble(), mapView.mapScale)
                mapView.setViewpointAsync(v, 2f)
            }
        }

        district.setInitDataListener(object : InitDataListener {
            override fun initData() {
                if (citys.isEmpty()) {
                    return
                }
                district.showPopWindow()
            }
        })
        district.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                /*if ("update" == action) {
                    if (s.toString().equals(cityNames)) {

                    } else {
                        cityNames = s.toString()
                        township.setText("")
                        village.setText("")
                        disasterName.setText("")
                        disasterNum.setText("")
                    }
                }*/
                if (district.isTextChanged) {
                    isSelectCity = true
                    township.text = ""
                    disasterName.setText("")
                    disasterNum.text = ""
                    village.setText("")
                    isSelectCity = false
                }
            }

        })

        township.setInitDataListener(object : InitDataListener {
            override fun initData() {
                if (district.text.isNotEmpty()) {
                    if ("update" == action && district.getmPosition() == -1) {
                        mPresenter.requestListTown(token, tapInfo.data!!.city)
                    } else {
                        val indexOf = citys.indexOf(district.text.toString())
                        if (indexOf == -1) {
                            showLongToast("请输入正确的区县名称!")
                            return
                        }
                        val id = if (district.getmPosition() == -1) {
                            listCitys[indexOf].id
                        } else {
                            listCitys[district.getmPosition()].id
                        }
                        mPresenter.requestListTown(token, id)
                    }
                } else {
                    showLongToast("请先选择区县!")
                }
            }

        })
        township.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (township.isTextChanged) {
                    isSelectTown = true
                    disasterName.setText("")
                    disasterNum.text = ""
                    village.setText("")
                    isSelectTown = false
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        disasterName.setInitDataListener {
            if (township.text.isNotEmpty()) {
                if ("update" == action && township.getmPosition() == -1) {
                    mPresenter.requestListDisaster(token, 1, 1000000, tapInfo.data!!.areaCode!!)
                } else {
                    val areaCode = listTowns[township.getmPosition()].areaCode
                    mPresenter.requestListDisaster(token, 1, 1000000, areaCode!!)
                }
            } else {
                showLongToast("请先选择乡镇!")
            }
        }
        disasterName.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (disasterName.isTextChanged) {
                    disasterNum.text = ""
                }

                if (!disasterName.isMySelected && !isSelectCity && !isSelectTown && !isFirstUpdate) {
                    if (district.text.isEmpty()) {
                        CustomToast.showToast(context, "请选择区县")
                        return
                    }
                    if (township.text.isEmpty()) {
                        CustomToast.showToast(context, "请选择乡镇")
                        return
                    }
                    if (p0.toString().isEmpty()) {
                        return
                    }
                    if ("update" == action && township.getmPosition() == -1) {
                        mPresenter.requestDisName(token, p0.toString(), tapInfo.data!!.townCode!!)
                    } else {
                        mPresenter.requestDisName(token, p0.toString(), listTowns[township.getmPosition()].areaCode!!)
                    }
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

        })

        disasterNum.setInitDataListener {
            if (disasterName.text.isNotEmpty()) {
                if ("update" == action && township.getmPosition() == -1) {
                    mPresenter.requestDisNum(token, disasterName.text.toString(), tapInfo.data!!.areaCode!!)
                } else {
                    val areaCode = listTowns[township.getmPosition()].areaCode
                    mPresenter.requestDisNum(token, disasterName.text.toString(), areaCode!!)
                }
            } else {
                showLongToast("请先选择灾害点名称!")
            }
        }

        monitorType.setInitDataListener {
            monitorType.showPopWindow()
        }

        serialNumber.setInitDataListener {
            serialNumber.showPopWindow()
        }
    }

    private fun checkInfo(): Boolean {
        if (district.text.toString().isEmpty()) {
            initTipsDialog("请输入或选择区县")
            return true
        }

        if (township.text.toString().isEmpty()) {
            initTipsDialog("请输入或选择乡镇")
            return true
        }

        if (village.text.toString().isEmpty()) {
            initTipsDialog("请输入村组")
            return true
        }

        if (disasterName.text.toString().isEmpty()) {
            initTipsDialog("请输入或选择灾害点名称")
            return true
        }

        if (disasterNum.text.toString().isEmpty()) {
            initTipsDialog("请输入或选择灾害点编号")
            return true
        }

        if (monitorType.text.toString().isEmpty()) {
            initTipsDialog("请输入或选择监测类型")
            return true
        }

        if (serialNumber.text.toString().isEmpty()) {
            initTipsDialog("请输入或选择序号")
            return true
        }
        return false
    }

    override fun uploadPicSuccess(result: UploadPicBean) {
        if (result.data.isNotEmpty()) {
            picString = result.data
            selImageList.clear()
            val imageItem = ImageItem()
            imageItem.name = result.data.substring(result.data.lastIndexOf("/") + 1)
            //"${Constant.fileUrl}"+path+"&type=6"
            imageItem.path = "${Constant.fileUrl}${result.data}&type=6"
            imageItem.mimeType = result.data
            selImageList.add(imageItem)
            adapter.images = selImageList
        }
    }

    override fun removePicFile(result: RemovePicBean) {
        picString = ""
        selImageList.removeAll(deleteImageList)
        adapter.images = selImageList
    }

    override fun handlerUpdateTapResult(result: TapAddResultBean) {
        if (result.isData) {
            val intent = Intent(context, UploadSuccessEquipmentActivity::class.java)
            intent.putExtra("imgPath", picString)
            startActivity(intent)
            finish()
        } else {
            if (result.code == 601) {
                showShortToast("序号已使用,请重新选择序号!")
            }
        }
    }

    override fun handlerAddTapResult(result: TapAddResultBean) {
        if (result.isData) {
            val intent = Intent(context, UploadSuccessEquipmentActivity::class.java)
//            intent.putExtra("imgPath", tapInfo.data!!.pointPic)
            intent.putExtra("imgPath", picString)
            startActivity(intent)
            finish()
        } else {
            if (result.code == 601) {
                showShortToast("序号已使用,请重新选择序号!")
            }
        }
    }

    override fun handlerListCityResult(result: CityBean) {
        listCitys.clear()
        listCitys.addAll(result.data!!)
        citys.clear()
        result.data?.forEach {
            citys.add(it.areaName!!)
        }
        cityAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, citys)
        district.setAdapter(cityAdapter)

    }

    override fun handlerListTownResult(result: TownBean) {
        listTowns.clear()
        listTowns.addAll(result.data!!)
        towns.clear()
        result.data?.forEach {
            towns.add(it.areaName!!)
        }
        townAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, towns)
        township.setAdapter(townAdapter)
        township.showPopWindow()
    }

    override fun handlerListDisasterResult(result: DisasterBean) {
        if (result.data!!.isNotEmpty()) {
            disastersName.clear()
            result.data?.forEach {
                disastersName.add(it.disasterName!!)
            }
            disasterNameAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersName)
            disasterName.setAdapter(disasterNameAdapter)
            disasterName.showPopWindow()
        } else {
            showShortToast("没有相关灾害点!")
        }
    }

    override fun handlerDisNum(result: DisNumBean) {
        disastersNu.clear()
        result.data?.forEach {
            disastersNu.add(it)
        }
        disasterNuAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersNu)
        disasterNum.setAdapter(disasterNuAdapter)
        disasterNum.showPopWindow()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQ_CODE_SELECT) {
                val images = data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>
                mPresenter.requestUploadPic(token, File(images[0].path), 6)
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQ_CODE_PREVIEW) {
                val images = data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS) as ArrayList<ImageItem>
                deleteImageList.clear()
                deleteImageList.addAll(selImageList)
                deleteImageList.removeAll(images)
                if (deleteImageList.isNotEmpty()) {
                    mPresenter.requestRemovePicFile(token, deleteImageList[0].mimeType, 6)
                }
            }
        }
    }

    override fun handlerDisNameResult(result: DisNameBean) {
        if (result.data!!.records!!.isNotEmpty()) {
//            var disastersName = mutableListOf<String>()
            disastersName.clear()
            result.data?.records?.forEach {
                disastersName.add(it.disasterName!!)
            }
            disasterNameAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, disastersName)
            disasterName.setAdapter(disasterNameAdapter)
            disasterName.showPopWindow()
        } /*else {
            showShortToast("没有相关灾害点!")
        }*/
    }

    override fun onError(msg: String, code: Int) {
        CustomToast.showToast(context, msg)
    }

    override fun showLoading() {

    }

    override fun hideLoading() {
    }

    override fun onPause() {
        if (mapView != null) {
            mapView.pause()
        }
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        if (mapView != null) {
            mapView.resume()
        }
    }

    override fun onDestroy() {
        if (mapView != null) {
            mapView.dispose()
        }
        super.onDestroy()
    }

    @SuppressLint("SetTextI18n", "InflateParams")
    private fun initDialog() {
        val inflate = LayoutInflater.from(context).inflate(R.layout.equipment_step_dialog, null)
        inflate.address.text = "${district.text}${township.text}${village.text}"
        inflate.disasterName.text = "${disasterName.text}"
        inflate.disasterNum.text = "${disasterNum.text}"
        inflate.monitorType.text = "${monitorType.text}"
        inflate.serialNumber.text = "${serialNumber.text}"
        //inflate.serialNumber.text = "${serialNumber.text}"
        inflate.currlon.text = "${lon.text}"
        inflate.currlat.text = "${lat.text}"
        val show = android.app.AlertDialog.Builder(context)
                .setView(inflate)
                .setCancelable(false)
                .show()
        inflate.cancel.setOnClickListener {
            show.dismiss()
        }
        inflate.submit.setOnClickListener {
            if ("add" == action) {
                monitorNo = strMonitorNo[monitorType.getmPosition()] + strSerialNumber[serialNumber.getmPosition()]
                val tapAddDTO = TapAddDTO()
                tapAddDTO.areaCode = listTowns[township.getmPosition()].areaCode!!
                tapAddDTO.village = village.text.toString()
                tapAddDTO.disNo = disasterNum.text.toString()
                tapAddDTO.monitorType = monitorType.getmPosition()
                tapAddDTO.monitorTypeName = monitorType.text.toString()
                tapAddDTO.disName = disasterName.text.toString()
                tapAddDTO.monitorMethod = 1
                tapAddDTO.pointPic = picString
                tapAddDTO.monitorNo = monitorNo
                tapAddDTO.monitorLat = lat.text.toString()
                tapAddDTO.monitorLng = lon.text.toString()
                tapAddDTO.isAppAdd = 1
                mPresenter.requestAddTap(token, tapAddDTO)
            } else if ("update" == action) {
                val strMonitorNo1: String
                val strSeriNum: String = if (serialNumber.getmPosition() == -1) {
                    tapInfo.data!!.monitorNo!!.substring(tapInfo.data!!.monitorNo!!.length - 2,
                            tapInfo.data!!.monitorNo!!.length)
                } else {
                    strSerialNumber[serialNumber.getmPosition()]
                }
                val tapAddDTO = TapAddDTO()
                if (township.getmPosition() == -1) {
                    tapAddDTO.areaCode = tapInfo.data!!.areaCode!!
                } else {
                    tapAddDTO.areaCode = listTowns[township.getmPosition()].areaCode!!
                }

                if (disasterNum.getmPosition() == -1) {
                    tapAddDTO.disNo = tapInfo.data!!.disNo!!
                } else {
                    tapAddDTO.disNo = disasterNum.text.toString()
                }

                if (monitorType.getmPosition() == -1) {
                    tapAddDTO.monitorType = tapInfo.data!!.monitorType!!.toInt()
                    strMonitorNo1 = tapInfo.data!!.monitorNo!!.removeRange(tapInfo.data!!.monitorNo!!.length - 2,
                            tapInfo.data!!.monitorNo!!.length)
                } else {
                    tapAddDTO.monitorType = monitorType.getmPosition()
                    strMonitorNo1 = strMonitorNo[monitorType.getmPosition()]
                }

                tapAddDTO.village = village.text.toString()
                tapAddDTO.monitorMethod = 1
                tapAddDTO.pointPic = picString
                tapAddDTO.monitorNo = strMonitorNo1 + strSeriNum
                tapAddDTO.monitorLat = lat.text.toString()
                tapAddDTO.monitorLng = lon.text.toString()
                tapAddDTO.monitorTypeName = monitorType.text.toString()
                tapAddDTO.disName = disasterName.text.toString()
                tapAddDTO.isAppAdd = 1
                tapAddDTO.id = tapInfo.data!!.id

                mPresenter.requestUpdateTap(token, tapAddDTO)
            }

            show.dismiss()
        }
    }

    @SuppressLint("SetTextI18n", "InflateParams")
    private fun initTipsDialog(s: String) {
        val inflate = LayoutInflater.from(context).inflate(R.layout.dialog_tips, null)
        inflate.tips.text = "温馨提示"
        inflate.content.text = s
        val show = android.app.AlertDialog.Builder(context)
                .setView(inflate)
                .setCancelable(false)
                .show()
        inflate.cancels.setOnClickListener {
            show.dismiss()
        }
    }


    private fun setLocationPointOverlay(long: Double, latu: Double) {
        lon.text = long.toString()

        lat.text = latu.toString()
        val simpleMarkerSymbol = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 20F)

        val point = Point(long, latu, SpatialReferences.getWgs84())
        val graphic = Graphic(point, simpleMarkerSymbol)
        graphic.zIndex = 0x110
        mGraphicsOverlay.graphics.add(graphic)
        mapView.graphicsOverlays.add(mGraphicsOverlay)
        val v = Viewpoint(latu, long, 10000.toDouble())
        mapView.setViewpointAsync(v, 2F)

    }

    override fun onBackPressed() {
        var content = ""
        if ("add" == action) {
            content = "返回后将清空已填内容,确认返回？"
        } else if ("update" == action) {
            content = "修改内容不会被保存,确认返回？"
        }
        MaterialDialog.Builder(this)
                .title("提示")
                .content(content)
                .positiveText("确认")
                .negativeText("取消")
                .onPositive { _, _ -> finish() }
                .show()
    }
}
